<template>
  <div class="innerPageTable-box-OneTwo value-set-list-wrap innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="serviceForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <Form-item prop="areacode" :label="'表单名称：'">
          <Select filterable v-model="searchForm.areacode">
            <Option v-for="item in areaCodeList" :value="item.key" :key="item.key">{{ item.value }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="buname" :label="'单位名称：'">
          <Select filterable clearable v-model="searchForm.buname" v-if="isNew">
            <Option v-for="item in filterOrgList" :value="item.orgCode" :key="item.orgCode">{{ item.orgName }}</Option>
          </Select>
          <Select filterable clearable v-model="searchForm.buname" v-else>
            <Option v-for="item in bussinessUnit" :value="item" :key="item">{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="period" :label="'填报周期：'">
          <Select filterable v-model="searchForm.period">
            <Option v-for="item in periodList" :value="item.value" :key="item.value">{{ item.text }}</Option>
          </Select>
        </Form-item>
        <Form-item prop="statusCode" :label="'状态：'">
          <Select filterable clearable v-model="searchForm.statusCode">
            <Option v-for="item in fillingStatusList" :value="item.value" :key="item.value">{{ item.text }}</Option>
          </Select>
        </Form-item>

        <!-- 查询\重置按钮 -->
        <Form-item prop="button" class="search-solt-btn">
          <RPButton optType="search" ref="search" @click="searchValueSet()" />
          <RPButton btnType="default" text="重置" @click="handleReset" />
        </Form-item>
      </Form>
    </SelfAdaption>

    <InnerPageTable ref="valueSetTable" :config="pageTableConfig"> </InnerPageTable>
  </div>
</template>

<script>
import { columnListFilling } from './columns'
import todoApi from '@/api/todoCender.js'
import coverApi from '@/api/cover.js'
import { FILLING_STATUS_LIST } from './const.js'
import formCenterApi from '@/api/formCenter.js'
import { findObjectByValue } from '../utils/index'
import { mapState } from 'vuex'
export default {
  name: 'filling',
  mixins: [],
  props: {
    // areaCodeList: {
    //   type: Array,
    //   default: () => []
    // },
  },
  computed: {
    ...mapState(['orgList', 'menuList'])
  },
  data() {
    return {
      isNew: false,
      newAreaCodeList: [],
      filterOrgList: [],
      areaCodeList: [],
      allAreaList: [],
      // allPeriodList: [],
      bussinessUnit: [],
      periodList: [],
      fillingStatusList: FILLING_STATUS_LIST,
      searchForm: {
        areacode: '',
        areaname: '',
        buname: '',
        period: '',
        status: '',
        statusCode: ''
      },
      tableData: [],
      pageTableConfig: {
        loadDataFn: this.getFillingInfoList,
        columns: columnListFilling.bind(this)(),
        pageSize: 50,
        autoFirst: false //默认 就是 false, 要配置在这里
      }
    }
  },
  watch: {
    'searchForm.areacode': {
      async handler(val) {
        if (val) {
          const item = this.newAreaCodeList.find(item => item.key == val)
          if (item) {
            // 表单中心的数据--获取填报周期
            const res = await formCenterApi.formReportHistoryPeriod([val])
            this.periodList = []
            Array.from(new Set(res.data)).forEach(item => {
              this.periodList.push({ value: item, text: item })
            })
            // 获取单位名称
            const unitCodeList = await todoApi.getOrgList(item.bpmId)
            const result = unitCodeList.map(id => findObjectByValue(this.orgList, id)).filter(item => item !== null)
            this.filterOrgList = result
            this.searchForm.buname = this.filterOrgList[0]?.orgCode
            this.searchForm.period = this.periodList[0]?.value
            this.isNew = true
          } else {
            this.$set(this.searchForm, 'period', '')
            this.$set(this.searchForm, 'buname', '')
            this.getBussinessUnit()
            let areaCodeKey = this.areaCodeList.filter(item => item.key == val)[0].key
            let tempList = val ? this.allAreaList.filter(item => item.vsiKey == areaCodeKey) : []
            this.periodList = []
            try {
              this.periodList = tempList && tempList.length > 0 ? JSON.parse(tempList[0].vsiDescription) : []
              let defaultPeriod = this.periodList.filter(item => item.default == 'Y')[0]?.value || ''
              this.$set(this.searchForm, 'period', defaultPeriod)
            } catch (error) {
              console.log(error)
            }
            this.isNew = false
          }
          this.$refs['valueSetTable'].load(this.searchForm)
        }
      },
      immediate: true
    }
  },
  methods: {
    getBussinessUnit() {
      if (this.searchForm.areaname) {
        todoApi.getBussinessUnit({ areaCode: this.searchForm.areacode }).then(res => {
          if (res.data.code == 200) {
            this.bussinessUnit = res.data.data ? res.data.data.map(item => item.value) : []
          }
        })
      } else {
        this.bussinessUnit = []
      }
    },
    getFillingInfoList(tableObj) {
      let { responseProcess, param } = tableObj
      let { pageNum, pageSize, areacode, areaname, buname, period, statusCode, status } = param
      if (this.newAreaCodeList.find(item => item.key == areacode)) {
        //表单数据
        formCenterApi
          .reportFindList({
            formId: areacode,
            period,
            state: statusCode,
            org: buname
          })
          .then(res => {
            let records = res.data.data || []
            records.forEach(item => {
              item.areaname = item.formName
              item.buname = this.filterOrgList.find(org => org.orgCode === item.org)?.orgName
              item.status = item.state == 0 ? '未填报' : '已填报'
            })
            responseProcess({
              pageNum,
              size: pageSize,
              records: records,
              total: records.length
            })
          })
      } else {
        todoApi
          .getFillingInfoList({
            areacode,
            areaname,
            buname,
            period,
            statusCode,
            status,
            pageNum,
            pageSize
          })
          .then(res => {
            let { records } = res.data.data
            responseProcess({
              pageNum: 1,
              size: 1,
              pages: 1,
              records: records || [],
              total: records.length
            })
          })
      }
    },
    //搜索
    searchValueSet() {
      let areaname = this.areaCodeList.filter(item => item.key == this.searchForm.areacode)[0].value
      let status = this.searchForm.statusCode
        ? this.fillingStatusList.filter(item => item.value == this.searchForm.statusCode)[0].text
        : ''
      this.$set(this.searchForm, 'areaname', areaname)
      this.$set(this.searchForm, 'status', status)
      this.$refs['valueSetTable'].load(this.searchForm)
    },
    handleReset() {
      this.searchForm.buname = ''
      this.searchForm.period = ''
      this.searchForm.statusCode = ''
      this.$refs['valueSetTable'].load(this.searchForm)
    }
  },
  async created() {
    const areaCodeListRes = await todoApi.getAreaCodeList()
    if (areaCodeListRes.data.code == 200) {
      this.areaCodeList = areaCodeListRes.data.data || []
    }
    const newAreaCodeRes = await formCenterApi.getNewAreaCodeList()
    //表单中心的数据
    if (newAreaCodeRes.data.code == 200) {
      this.newAreaCodeList = []
      const data = newAreaCodeRes.data.data || []
      data.forEach(element => {
        this.newAreaCodeList.push({ key: element.id, value: element.name, bpmId: element.bpmpId })
        this.areaCodeList.push({ key: element.id, value: element.name, bpmId: element.bpmpId })
      })
    }
    const codeListRes = await coverApi.getCodeList('AREA')
    this.allAreaList = codeListRes.data.records || []
    // 查询完填报周期，设置领域默认值
    this.$set(this.searchForm, 'areacode', this.areaCodeList[0].key)
    this.$set(this.searchForm, 'areaname', this.areaCodeList[0].value)
    if (this.orgList.length <= 0) {
      this.$store.dispatch('getOrgList')
    } else {
      this.filterOrgList = this.orgList.filter(item => !item.children)
    }
  },
}
</script>
<style lang="less" scoped>
/deep/.table-bar button:last-child {
  color: #ffffff;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
}

/deep/ .self-adaption-wrap .self-adaption-flex {
  margin-bottom: 0px;
}
</style>

<style lang="less">
.icon-box {
  line-height: 30px;
  .ivu-icon {
    font-size: 28px;
  }
  .ivu-icon-ios-checkmark-circle {
    font-size: 28px;
    color: #19be6b;
  }
  .ivu-icon-ios-alert {
    font-size: 28px;
    color: #f90;
  }
  span {
    font-weight: bold;
    display: inline-block;
    vertical-align: top;
    margin-left: 5px;
  }
  p {
    margin-top: 10px;
    padding-left: 34px;
  }
  /deep/.ivu-btn-text {
    color: red;
    border: 1px solid transparent;
    // &:hover{
    //    border: 1px solid #ff6f4b
    // }
  }
}
</style>
